/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.meraklisina.latexeditor.mdi.DialogActions;


import java.io.*;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTabbedPane;

import com.meraklisina.latexeditor.mdi.Common.FileOperations;
import com.meraklisina.latexeditor.mdi.Common.Tools;
import com.meraklisina.latexeditor.mdi.FileFilters.FileFilterTEX;
import com.meraklisina.latexeditor.mdi.TextEditor.TextEditors;

/**
 *
 * @author Eray
 */
public class ActionOpen
{
    TextEditors ClsTextEditor = new TextEditors();
    FileOperations ClsFile = new FileOperations();

    /**
     * Displays an OpenDialog for the given JTabbedPane.
     *
     * @param TabEditors
     */
    public void OpenDialog(JTabbedPane TabEditors)
    {
        JFileChooser fileChooser = new JFileChooser();
        File lastOpen = new File(Tools.getLastOpenedDirectory());

        fileChooser.setCurrentDirectory(lastOpen);
        fileChooser.setDialogTitle("Open");
        fileChooser.setFileFilter(new FileFilterTEX());

        int returnValue = fileChooser.showOpenDialog(null);
        if (returnValue == JFileChooser.APPROVE_OPTION)
        {
              File selectedFile = fileChooser.getSelectedFile();
              Tools.setLastOpenedDirectory(fileChooser.getSelectedFile().getPath());

              boolean IsFileExist = false;

              for(TextEditors editor : ClsTextEditor.getEditors())
              {
                  if(editor.getRealPath().equals(selectedFile.getPath()))
                  {
                      JOptionPane.showMessageDialog(null,"This file is already opened.","File Warning",JOptionPane.WARNING_MESSAGE);
                      IsFileExist = true;
                      break;
                  }

              }

              if(!IsFileExist)
              {
                  if(ClsTextEditor.GetScrapPath(TabEditors.getSelectedIndex()).isEmpty() && ClsTextEditor.GetRealPath(TabEditors.getSelectedIndex()).isEmpty() && !ClsTextEditor.GetIsTextChanged(TabEditors.getSelectedIndex()))
                  {
                      ClsFile.ReadFileWriteTextField(ClsTextEditor.GetJTextPaneAt(TabEditors, TabEditors.getSelectedIndex()), selectedFile);
                      ClsTextEditor.SetRealPath(TabEditors.getSelectedIndex(), selectedFile.getPath());
                      TabEditors.setTitleAt(TabEditors.getSelectedIndex(), selectedFile.getName());

                  }
                  else
                  {
                      ClsTextEditor.AddTab(TabEditors, false, "", selectedFile.getPath(), selectedFile);
                  }
              }
              //SetTextChange(Form, false);
        }
     }
}
